package datastructure.map;

import utils.printer.BinaryTreeInfo;
import utils.printer.BinaryTrees;

import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;

/**
 * @Description: 使用哈希表实现 Map
 * @Author Ammar
 * @Create 2023/4/21 22:04
 */
public class HashMap<K, V> implements Map<K, V> {
    private static final boolean RED = false;
    private static final boolean BLACK = true;
    // 默认容量
    private static final int DEFAULT_CAPACITY = 1 << 4;
    // 装载因子
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;
    // 数组
    private Node<K, V>[] table;
    // 元素个数
    private int size;

    public HashMap() {
        table = new Node[DEFAULT_CAPACITY];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        if (size == 0) return;
        size = 0;
        int len = table.length;
        for (int i = 0; i < len; i++) {
            table[i] = null;
        }
    }

    // stg
    // sort
    @Override
    public V put(K key, V value) {
        // 扩容
        resize();
        // 找出数组对应的索引
        int index = index(key);
        // 获取索引对应的红黑树根节点
        Node<K, V> root = table[index];
        // 如果根节点为空，说明该索引位置没有元素，直接添加
        if (root == null) {
            root = createNode(key, value, null);
            table[index] = root;
            size++;
            fixAfterPut(root);
            return null;
        }
        // 根节点不为空，添加新节点到红黑树上
        Node<K, V> node = root;
        // 记录新节点要添加到哪个父节点下面
        Node<K, V> parent = root;
        K key1 = key;
        int hash1 = hash(key1);
        // 记录比较结果
        int cmp = 0;
        // 记录左子树中相同的节点
        Node<K, V> sameNode = null;
        // 记录是否遍历过全部节点
        boolean searched = false;
        do {
            parent = node;
            K key2 = node.key;
            int hash2 = node.hash;
            if (hash1 > hash2) {
                cmp = 1;
            } else if (hash1 < hash2) {
                cmp = -1;
            } else if (Objects.equals(key1, key2)) {
                cmp = 0;
            } else if (key1 != null && key2 != null
                    && key1 instanceof Comparable
                    && key1.getClass() == key2.getClass()
                    && (cmp = ((Comparable<K>) key1).compareTo(key2)) != 0) {
            } else if (searched) {
                cmp = System.identityHashCode(key1) - System.identityHashCode(key2);
            } else if ((node.left != null && (sameNode = node(node.left, key1)) != null)
                    || (node.right != null && (sameNode = node(node.right, key1)) != null)) {
                node = sameNode;
                cmp = 0;
            } else {
                searched = true;
                /**
                 * hash1 == hash2 && !key1.equals(key2) && key1.compareTo(key2) == 0
                 * && 在 node 的左右子树中没有找到相同的节点
                 */
                cmp = System.identityHashCode(key1) - System.identityHashCode(key2);
            }

            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {
                // 相等，替换值
                V oldValue = node.value;
                node.key = key;
                node.value = value;
                node.hash = hash1;
                return oldValue;
            }
        } while (node != null);

        // 添加新节点
        Node<K, V> newNode = createNode(key, value, parent);
        if (cmp > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        size++;
        // 新添加节点之后的平衡红黑树
        fixAfterPut(newNode);
        return null;
    }

    @Override
    public V get(K key) {
        Node<K, V> node = node(key);
        return node == null ? null : node.value;
    }

    @Override
    public V remove(K key) {
        return remove(node(key));
    }

    @Override
    public boolean containsKey(K key) {
        return node(key) != null;
    }

    @Override
    public boolean containsValue(Object value) {
        if (size == 0) return false;
        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < table.length; i++) {
            if (table[i] == null) continue;
            queue.offer(table[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (Objects.equals(node.value, value)) return true;
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
        return false;
    }

    @Override
    public void traversal(Visitor visitor) {
        if (size == 0 || visitor == null) return;
        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < table.length; i++) {
            if (table[i] == null) continue;
            queue.offer(table[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (visitor.visit(node.key, node.value)) return;
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
    }

    // 扩容
    private void resize() {
        // 如果装填因子小于默认值，不需要扩容
        if (size / table.length <= DEFAULT_LOAD_FACTOR) return;
        // 扩容为原来的 2 倍
        Node<K, V> oldTable[] = table;
        table = new Node[oldTable.length << 1];
        // 重新计算索引
        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < oldTable.length; i++) {
            if (oldTable[i] == null) continue;
            queue.offer(oldTable[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
                // 挪动节点到新的桶
                moveNode(node);
            }
        }
    }

    // 挪动节点到新的桶
    private void moveNode(Node<K, V> newNode) {
        // 重置
        newNode.parent = null;
        newNode.left = null;
        newNode.right = null;
        newNode.color = RED;
        // 获取根节点
        int index = index(newNode);
        Node<K, V> root = table[index];
        if (root == null) {
            root = newNode;
            table[index] = root;
            fixAfterPut(root);
            return;
        }

        // 添加新节点到红黑树上
        Node<K, V> parent = root;
        Node<K, V> node = root;
        K key1 = newNode.key;
        int hash1 = newNode.hash;
        int cmp = 0;
        do {
            parent = node;
            K key2 = node.key;
            int hash2 = node.hash;
            if (hash1 > hash2) {
                cmp = 1;
            } else if (hash1 < hash2) {
                cmp = -1;
            } else if (key1 != null && key2 != null
                    && key1 instanceof Comparable
                    && key1.getClass() == key2.getClass()
                    && (cmp = ((Comparable) key1).compareTo(key2)) != 0) {
            } else {
                cmp = System.identityHashCode(key1) - System.identityHashCode(key2);
            }

            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            }
        } while (node != null);

        newNode.parent = parent;
        if (cmp > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }

        fixAfterPut(newNode);
    }

    private Node<K, V> node(K key) {
        return node(table[index(key)], key);
    }

    // 根据 root 和 key 获取对应的节点
    private Node<K, V> node(Node<K, V> root, K key1) {
        int hash1 = hash(key1);
        Node<K, V> someNode = null;
        int cmp = 0;
        Node<K, V> node = root;
        while (node != null) {
            K key2 = node.key;
            int hash2 = node.hash;
            if (hash1 > hash2) {
                node = node.right;
            } else if (hash1 < hash2) {
                node = node.left;
            } else if (Objects.equals(key1, key2)) {
                return node;
            } else if (key1 != null && key2 != null
                    && key1 instanceof Comparable
                    && key1.getClass() == key2.getClass()
                    && (cmp = ((Comparable<K>) key1).compareTo(key2)) != 0) {
                node = cmp > 0 ? node.right : node.left;
            } else if (node.left != null && (someNode = node(node.left, key1)) != null) {
                return someNode;
            } else {
                node = node.right;
            }
        }
        return null;
    }

    // 根据 key 获取node
    private int index(Node<K, V> node) {
        return node.hash & (table.length - 1);
    }

    // 根据 key 获取对应的索引
    private int index(K key) {
        return hash(key) & (table.length - 1);
    }

    // 计算 key 的哈希值
    private int hash(K key) {
        if (key == null) return 0;
        int hash = key.hashCode();
        return hash ^ (hash >>> 16);
    }

    // 删除节点
    protected V remove(Node<K, V> node) {
        if (node == null) return null;
        // 记录node
        Node<K, V> willNode = node;
        size--;
        V oldValue = node.value;
        // 度为 2 的节点
        if (node.hasTwoChildren()) {
            // 找到后继节点
            Node<K, V> s = successor(node);
            // 用后继节点的值覆盖度为 2 的节点的值
            node.key = s.key;
            node.value = s.value;
            node.hash = s.hash;
            // 删除后继节点
            node = s;
        }
        // 删除 node 节点（node 的度必然是 1 或者 0）
        Node<K, V> replacement = node.left != null ? node.left : node.right;
        int index = index(node);
        // node 是度为 1 的节点
        if (replacement != null) {
            // 将替代节点的父节点指向 node 的父节点
            replacement.parent = node.parent;
            // 更改 parent 的 left、right 的指向
            // node 是度为1的根节点
            if (node.parent == null) {
                table[index] = replacement;
            } else if (node == node.parent.left) {
                node.parent.left = replacement;
            } else {
                node.parent.right = replacement;
            }

            // 删除节点之后恢复红黑树平衡
            fixAfterRemove(node, replacement);
        }
        // node 是叶子节点并且是根节点
        else if (node.parent == null) {
            table[index] = replacement;
        }
        // node 是叶子节点，不是根节点
        else {
            if (node == node.parent.left) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }
            fixAfterRemove(node, null);
        }

        afterRemove(willNode, node);
        return oldValue;
    }

    protected void afterRemove(Node<K, V> willNode, Node<K, V> removedNode) {
    }


    protected void fixAfterPut(Node<K, V> node) {
        Node<K, V> parent = node.parent;

        // 添加的是根节点
        if (parent == null) {
            black(node);
            return;
        }
        // 如果父节点是黑色，直接返回
        if (isBlack(parent)) return;

        // uncle节点
        Node<K, V> uncle = parent.sibling();
        Node<K, V> grand = red(parent.parent);

        // 如果uncle节点是红色，上溢
        // 不管是哪种情况，都要将 grand 节点染成红色，parent 和 uncle 节点染成黑色
        if (isRed(uncle)) {
            black(parent);
            black(uncle);
            // 把祖父节点当做是新添加的节点
            fixAfterPut(grand);
            return;
        }
        if (parent.isLeftChild()) { // L
            if (node.isLeftChild()) { // LL
                black(parent);
            } else { // LR
                black(node);
                rotateLeft(parent);
            }
            rotateRight(grand);
        } else { // R
            // red(grand);
            if (node.isLeftChild()) { // RL
                black(node);
                rotateRight(parent);
            } else { // RR
                black(parent);
            }
            rotateLeft(grand);
        }
    }

    protected void fixAfterRemove(Node<K, V> node, Node<K, V> replacement) {
        // 如果要删除的节点是红色，什么也不做
        if (isRed(node)) return;

        // 如果删除的是黑色且度为1的节点，用子节点替代，子节点必然是红色，将其染色黑色即可
        if (isRed(replacement)) {
            black(replacement);
            return;
        }

        Node<K, V> parent = node.parent;
        // 此时，红黑树只有一个根节点，
        // 如果还有其他节点，删除根节点时，实际上删除的是前驱或者后继节点
        if (parent == null) return;

        // 1.程序来到这里，说明删除的是度为0的节点
        // 2.按照4阶B树的性质，会产生下溢
        // 3.如果兄弟节点有 RED 子节点，则借过来，所以要获取兄弟节点，
        // 4.二叉树删除叶子节点后，parent.left/right 已经指向null了，但是node.parent还未清除
        //   根据红黑树的性质，黑色叶子节点必然有BLACK兄弟节点，否则不满足性质5
        //   因此，在节点删除后，判断 parent.left/right 哪边为空，就可以知道删除的节点在 parent 的哪边了
        //   有一种特殊情况，就是在度为0的BLACK节点被删除后，parent下溢，
        //   然而，parent没有RED的子节点，parent下溢以后导致grand下溢，又会调用 afterRemove，
        //   此时parent.left/right都不为空，因为grand只是下溢没有被删除，
        //   这时需要判断grand是grand.parent的left or right，此时才能找到grand的sibling
        boolean left = parent.left == null || node.isLeftChild();
        Node<K, V> sibling = left ? parent.right : parent.left;

        // node在parent左边
        if (left) {
            if (isRed(sibling)) {
                black(sibling);
                red(parent);
                rotateLeft(parent);
                sibling = parent.right;
            }
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean parentBlack = isBlack(parent);
                black(parent);
                red(sibling);
                if (parentBlack) {
                    fixAfterRemove(parent, null);
                }
            } else {
                if (isBlack(sibling.right)) {
                    rotateRight(sibling);
                    sibling = parent.right;
                }
                color(sibling, colorOf(parent));
                black(sibling.right);
                black(parent);
                rotateLeft(parent);
            }
        }
        // node在parent右边
        else {
            if (isRed(sibling)) {
                black(sibling);
                red(parent);
                rotateRight(parent);
                // 更换 sibling
                sibling = parent.left;
            }
            // sibling 左右子节点全是黑色
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                // parent 是否有 RED true 表示没有 RED
                boolean parentBlack = isBlack(parent);
                black(parent);
                red(sibling);
                if (parentBlack) {
                    fixAfterRemove(parent, null);
                }
            }
            // sibling 至少有一个红色子节点，将子节点借过来，需要旋转
            // 一共三种情况，一 sibling.right = RED LR
            // 二 sibling.left = RED LL
            // 三 sibling.left and sibling.right = RED LL
            else {
                // LR情况
                if (isBlack(sibling.left)) {
                    rotateLeft(sibling);
                    sibling = parent.left;
                }

                // 由于旋转之后再获取对应的节点会有问题，因此先染色，再旋转
                color(sibling, colorOf(parent));
                black(sibling.left);
                black(parent);
                rotateRight(parent);
            }
        }
    }

    protected void rotateLeft(Node<K, V> grand) {
        Node<K, V> parent = grand.right;
        Node<K, V> leftChild = parent.left;
        // 左旋转
        grand.right = leftChild;
        parent.left = grand;
        // 更新 parent 的 parent
        afterRotate(grand, parent, leftChild);
    }

    protected void rotateRight(Node<K, V> grand) {
        Node<K, V> parent = grand.left;
        Node<K, V> rightChild = parent.right;
        // 右旋转
        grand.left = rightChild;
        parent.right = grand;
        afterRotate(grand, parent, rightChild);
    }

    protected void afterRotate(Node<K, V> grand, Node<K, V> parent, Node<K, V> child) {
        // 让 parent 成为子树的根节点
        parent.parent = grand.parent;
        if (grand.isLeftChild()) {
            grand.parent.left = parent;
        } else if (grand.isRightChild()) {
            grand.parent.right = parent;
        } else {
            // grand 是 root 节点
            table[index(grand.key)] = parent;
        }

        // 更新 child 的 parent
        if (child != null) {
            child.parent = grand;
        }

        // 更新 grand 的 parent
        grand.parent = parent;
    }

    public Node<K, V> successor(Node<K, V> node) {
        Node<K, V> p = node.right;
        if (p != null) {
            while (p.left != null) {
                p = p.left;
            }
            return p;
        }

        while (node.parent != null && node == node.parent.right) {
            node = node.parent;
        }
        return node.parent;
    }

    private Node<K, V> color(Node<K, V> node, boolean color) {
        if (node == null) return node;
        ((Node<K, V>) node).color = color;
        return node;
    }

    // 将节点染成红色
    private Node<K, V> red(Node<K, V> node) {
        return color(node, RED);
    }

    // 将节点染成黑色
    private Node<K, V> black(Node<K, V> node) {
        return color(node, BLACK);
    }

    // 返回节点的颜色
    private boolean colorOf(Node<K, V> node) {
        return node == null ? BLACK : ((Node<K, V>) node).color;
    }

    // 判断节点是否为黑色
    private boolean isBlack(Node<K, V> node) {
        return colorOf(node) == BLACK;
    }

    // 判断节点是否为红色
    private boolean isRed(Node<K, V> node) {
        return colorOf(node) == RED;
    }

    protected Node<K, V> createNode(K key, V value, Node<K, V> parent) {
        return new Node<>(key, value, parent);
    }

    // 打印
    public void print() {
        if (size == 0) return;
        for (int i = 0; i < table.length; i++) {
            final Node<K, V> root = table[i];
            System.out.println("【index = " + i + "】");
            BinaryTrees.println(new BinaryTreeInfo() {
                @Override
                public Object string(Object node) {
                    return node;
                }

                @Override
                public Object root() {
                    return root;
                }

                @Override
                public Object right(Object node) {
                    return ((Node<K, V>) node).right;
                }

                @Override
                public Object left(Object node) {
                    return ((Node<K, V>) node).left;
                }
            });
            System.out.println("---------------------------------------------------");
        }
    }

    // 红黑树节点类
    protected static class Node<K, V> {
        int hash;
        K key;
        V value;
        Node<K, V> left;
        Node<K, V> right;
        Node<K, V> parent;
        boolean color = RED;

        public Node(K key, V value, Node<K, V> parent) {
            this.key = key;
            this.value = value;
            int hash = key == null ? 0 : key.hashCode();
            this.hash = hash ^ (hash >>> 16);
            this.parent = parent;
        }

        public boolean isLeaf() {
            return left == null && right == null;
        }

        public boolean hasTwoChildren() {
            return left != null && right != null;
        }

        public boolean isLeftChild() {
            return parent != null && this == parent.left;
        }

        public boolean isRightChild() {
            return parent != null && this == parent.right;
        }

        public Node<K, V> sibling() {
            if (isLeftChild()) return parent.right;
            if (isRightChild()) return parent.left;
            return null;
        }

        @Override
        public String toString() {
            return color == RED ? "R_" + key + "_" + value : "B_" + key + "_" + value;
        }
    }
}
